import logging

from flask import current_app, flash
from flask_admin.contrib.sqla import ModelView
from sqlalchemy.exc import IntegrityError

from poker_bot.admin_panel.app.views.admin_lte import AdminLTEModelView
from poker_bot.admin_panel.app.views.auth_mixin import AuthMixin

logger = logging.getLogger(__name__)


class MyBaseModelView(AuthMixin, AdminLTEModelView):
    page_size = 10
    edit_modal = True
    column_display_pk = True
    create_modal = True
    can_export = True
    can_view_details = True
    column_hide_backrefs = False
    details_modal = True
    can_set_page_size = True

    export_types = ["xlsx", "csv"]

    column_labels = {
        "created_at": "Дата создания",
        "updated_at": "Дата обновления",
    }

    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            if current_app.config.get(
                "ADMIN_RAISE_ON_INTEGRITY_ERROR",
                current_app.config.get("ADMIN_RAISE_ON_VIEW_EXCEPTION"),
            ):
                raise
            else:
                flash(
                    "Не удалось создать запись. %(error)s",
                    "error",
                )
                logger.exception(f"Failed to create record: {str(exc)}")
            return True

        return super(ModelView, self).handle_view_exception(exc)
